<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搜索结果 - SearchHub</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36BFFA',
                        neutral: '#F5F7FA',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .search-shadow {
                box-shadow: 0 1px 6px rgba(32, 33, 36, 0.28);
            }
            .result-card {
                transition: all 0.2s ease;
            }
            .result-card:hover {
                transform: translateX(4px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            }
        }
    </style>
</head>

<body class="font-inter bg-gray-50 text-dark min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-white border-b border-gray-200 py-3">
        <div class="container mx-auto px-4">
            <div class="flex items-center justify-between">
                <!-- Logo -->
                <a href="index.html"
                    class="text-2xl font-bold bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
                    SearchHub
                </a>

                <!-- 搜索框（结果页也保留搜索框） -->
                <div class="hidden md:block flex-grow max-w-2xl mx-8">
                    <div class="relative">
                        <input type="text" id="searchInput" placeholder="搜索任何内容..."
                            class="w-full pl-4 pr-4 py-2 rounded-full border border-gray-200 search-shadow focus:outline-none focus:ring-2 focus:ring-primary/30 transition-all duration-200 text-sm">
                        <button id="searchButton"
                            class="absolute right-2 top-1/2 transform -translate-y-1/2 bg-primary text-white px-3 py-1 rounded-full text-xs">
                            搜索
                        </button>
                    </div>
                </div>

            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-grow container mx-auto px-4 py-6">
        <!-- 搜索结果统计 -->
        <div class="mb-6 text-gray-500 text-sm">
            <p id="resultStats">正在搜索...</p>
        </div>

        <!-- 结果列表容器 -->
        <div id="resultsContainer" class="space-y-6 mb-10">
            <!-- 加载状态 -->
            <div class="flex justify-center py-10">
                <div class="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-primary"></div>
            </div>
        </div>

        <!-- 分页控件 -->
        <div id="pagination" class="flex justify-center mt-8 hidden">
            <div class="flex space-x-2">
                <button class="px-4 py-2 rounded border border-gray-300 text-gray-600 hover:bg-gray-50">上一页</button>
                <button class="px-4 py-2 rounded border border-primary bg-primary text-white">1</button>
                <button class="px-4 py-2 rounded border border-gray-300 text-gray-600 hover:bg-gray-50">2</button>
                <button class="px-4 py-2 rounded border border-gray-300 text-gray-600 hover:bg-gray-50">3</button>
                <button class="px-4 py-2 rounded border border-gray-300 text-gray-600 hover:bg-gray-50">下一页</button>
            </div>
        </div>
    </main>


    <script>
        // 从URL获取参数
        function getQueryParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }

        // 页面加载时自动获取参数并请求结果
        document.addEventListener('DOMContentLoaded', () => {
            const query = getQueryParam('query');
            if (query) {
                fetchSearchResults(query); // 请求并展示结果
            }
            else {
                // 如果没有关键词，跳回主页
                window.location.href = 'index.html';
            }
        });

        // 绑定结果页搜索框的事件
        document.getElementById('searchButton').addEventListener('click', () => {
            const query = searchInput.value.trim();
            if (query) {
                // 用window.open()在新标签页打开结果页
                window.open(`search-results.html?query=${encodeURIComponent(query)}`, '_blank');
                // 可选：搜索后清空输入框（根据需求决定是否保留）
                // searchInput.value = '';
            }
        });

        document.getElementById('searchInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                document.getElementById('searchButton').click();
            }
        });



        // 请求后端获取搜索结果
        function fetchSearchResults(query) {
            // 构造请求URL（替换为实际后端IP）
            const searchParam = `word=${encodeURIComponent(query)}`;
            const backendUrl = `http://175.178.50.213:8080/search?${searchParam}`;

            fetch(backendUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP 错误，状态码：${response.status}`);
                    }
                    return response.json();
                })
                .then(results => {
                    // 渲染结果
                    renderResults(results, query);
                })
                .catch(error => {
                    console.error("搜索失败：", error);
                    const resultsContainer = document.getElementById('resultsContainer');
                    resultsContainer.innerHTML = `
                        <div class="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
                            <p>搜索失败：无法连接到服务器，请稍后重试</p>
                        </div>
                    `;
                });
        }

        // 渲染搜索结果
        function renderResults(results, query) {
            const resultsContainer = document.getElementById('resultsContainer');
            const resultStats = document.getElementById('resultStats');
            const pagination = document.getElementById('pagination');

            // 更新结果统计
            resultStats.textContent = `找到约 ${results.length} 条结果（用时 0.${Math.floor(Math.random() * 50) + 10} 秒）`;

            if (results.length === 0) {
                // 无结果时显示
                resultsContainer.innerHTML = `
                    <div class="text-center py-10">
                        <i class="fa fa-search text-gray-300 text-5xl mb-4"></i>
                        <p class="text-gray-500">没有找到与“${query}”相关的结果</p>
                        <p class="text-gray-400 text-sm mt-2">请尝试其他关键词或检查拼写</p>
                    </div>
                `;
                return;
            }

            // 有结果时渲染列表
            let resultsHtml = '';
            results.forEach((item, index) => {
                resultsHtml += `
                    <div class="result-card bg-white p-5 rounded-lg border border-gray-100">
                        <div class="text-sm text-gray-500 mb-1">${item.url}</div>
                        <a href="${item.url}" target="_blank" class="text-primary text-lg font-medium hover:underline mb-2 block">
                            ${highlightKeyword(item.title, query)}
                        </a>
                        <p class="text-gray-600 text-sm">
                            ${highlightKeyword(item.content, query)}
                        </p>
                    </div>
                `;
            });

            resultsContainer.innerHTML = resultsHtml;
            pagination.classList.remove('hidden'); // 显示分页
        }

        // 高亮显示关键词
        function highlightKeyword(text, keyword) {
            if (!keyword) return text;
            const regex = new RegExp(`(${keyword})`, 'gi');
            return text.replace(regex, '<span class="bg-yellow-200">$1</span>');
        }
    </script>
</body>

</html>